import router from '@/router'
import store from '@/store/index';
import api from '../request/api.js';
//控制动态路由添加，避免重复添加路由
let addRouterFlag = false

/*路由拦截：进入路由前判断是否有token，没有token进入login页面 */
router.beforeEach((to, from, next) => {
    console.error(to.path)
    let token = localStorage.getItem("token")
    if (to.path === '/login') return next()
    if (!token) { return next('/login') }
    addDynamicMenuAndRoutes()
    next()
})

/*动态路由add*/
function addDynamicMenuAndRoutes() {
    if (!addRouterFlag) {
        addRouterFlag = true
            // 请求菜单数据接口
        api.menueTree().then(res => {
            if (res.code == 200) {
                localStorage.setItem("menueTree", JSON.stringify(res.data));
                // 添加动态路由
                let dynamicRoutes = addDynamicRoutes(res.data)
                router.options.routes[1].children = router.options.routes[1].children.concat(dynamicRoutes)
                router.addRoutes(router.options.routes);
            }
        });
    }
}

function addDynamicRoutes(menuList = [], routes = []) {
    var temp = []
    for (var i = 0; i < menuList.length; i++) {
        if (menuList[i].children && menuList[i].children.length >= 1) {
            temp = temp.concat(menuList[i].children)
        } else if (menuList[i].url && /\S/.test(menuList[i].url)) {
            menuList[i].url = menuList[i].url.replace(/^\//, '')

            /*  根据菜单URL动态加载vue组件，这里要求vue组件须按照url路径存储
                如url="/sys/user"，则组件路径应是"@/views/sys/user",否则组件加载不到
                如果url="/case",则组件路径应是"@/views/case/case  */
            let urlArray = menuList[i].url.split('/')
            let componentUrl = ''
            if (urlArray && urlArray.length > 1) {
                componentUrl = urlArray[0] + '/' + urlArray[1]
            } else {
                componentUrl = urlArray[0] + '/' + urlArray[0]
            }
            var route = {
                path: '/' + menuList[i].url,
                component: () =>
                    import (`@/views/${componentUrl}`),
                name: menuList[i].name,
                meta: {
                    icon: menuList[i].icon,
                    index: menuList[i].id,
                    parent: menuList[i].parentName
                }
            }
            routes.push(route)
        }
    }
    if (temp.length >= 1) {
        addDynamicRoutes(temp, routes)
    } else {
        console.log('动态路由加载...')
        console.log(routes)
        console.log('动态路由加载完成.')
    }
    return routes
}

export default router